package com.zhjhserver.utils;

import java.sql.*;
import java.util.ArrayList;
import java.util.Random;

import org.apache.mina.core.session.IoSession;

import net.sf.json.JSONObject;

public class Table
{
    private static final int SEAT_NUM = 7;

    private Room mRoom = null;
    private int mIndex = 0;
    private ArrayList<Seat> mSeatList = null;

    private int mStatus = 0;        // 状态
    private int mSingleMoney = 0;   // 单注
    private int mTotalMoney = 0;    // 总注
    private int mTurnNum = 0;       // 轮数

    public Table(Room room, int index)
    {
        mRoom = room;
        mIndex = index;

        mSeatList = new ArrayList<Seat>();

        for (int i=0; i<SEAT_NUM; i++)
        {
            Seat seat = new Seat(this, i);
            mSeatList.add(seat);
        }
    }

    public int getIndex()
    {
        return mIndex;
    }

    public Room getRoom()
    {
        return mRoom;
    }

    public int getStatus()
    {
        return mStatus;
    }

    public Seat fastFindSeat()
    {
        int[] idles = new int[SEAT_NUM];
        int idleNum = 0;
        int i = 0;

        for (Seat seat: mSeatList)
        {
            if ( seat.isIdle() )
            {
                idles[idleNum++] = i;
            }

            i++;
        }

        if (idleNum == 0)
        {
            return null;
        }

        i = 0;

        if (idleNum > 2)
        {
            Random r = new Random();
            i = Math.abs(r.nextInt()) % idleNum;
        }

        return mSeatList.get(i);
    }

    public String getInfo()
    {
        JSONObject jsonOut = new JSONObject();
        jsonOut.put("status", mStatus);
        jsonOut.put("single_money", mSingleMoney);
        jsonOut.put("total_money", mTotalMoney);
        jsonOut.put("turn_num", mTurnNum);

        // 同桌玩家信息
        int i = 0;

        for (Seat seat: mSeatList)
        {
            jsonOut.put("p"+i, seat.getPlayerInfo());

            i++;
        }

        return jsonOut.toString();
    }

    // 通知同桌的其它玩家，有某个玩家的某种状态有了变化
    public void notify(Player player, int funcId)
    {
        String info = player.getInfo();

        byte[] data = info.getBytes();
		int len = Const.FUNC_ID_LEN + data.length;
		PackData pkg = new PackData(len);
		pkg.writeInt(funcId);
		pkg.writeBytes(data);

        for (Seat seat: mSeatList)
        {
            Player p = seat.getPlayer();

            if (p!=null && p != player)
            {
                IoSession session = p.getSession();
                session.write(pkg);
            }
        }
    }
}
